
<template>
  <div>
    <Content @InputFn="InputFn" @QueryFn="QueryFn" @configurationFn="configurationFn"
    @CheckDetailsFn="CheckDetailsFn" @OneBtn="OneBtn" @TwoBtn="TwoBtn" @OpenDiaFn="OpenDiaFn" @headerStyleEvent="headerStyleEvent"/>
    <!-- 弹出框 -->
    <!-- 新增工单 -->
    <ADDdialog
:outside-dialog-visible="OutsideDialogVisible"
title="新增工单"
@CloseDia="CloseDiaFn"
@OpenDia="OpenDia"
    >
      <template #Outside>
        <div>
          <!-- 表单内容 -->
          <el-form
            ref="departRef"
            :model="FromData"
            label-width="100px"
            :rules="departRules"
            size="small"
          >
            <el-form-item label="设备编号:" prop="innerCode" >
              <el-input
                v-model="FromData.innerCode"
                placeholder="请输入"
                @input="Operators"
              />
            </el-form-item>
            <el-form-item label="工单类型:" prop="productType">
              <el-select
                v-model="FromData.productType"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="补货工单" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="补货数量:" prop="num">
              <div class="txt">
                <i class="el-icon-edit-outline"> </i>
                <el-link
                  type="primary"
                  :underline="false"
                  @click.native="ReplenishmentFn"
                  >补货数量</el-link
                >
              </div>
            </el-form-item>
            <el-form-item label="运营人员:" prop="assignorId">
              <el-select
                v-model="FromData.assignorId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in OperatorsData"
                  :key="index"
                  :label="item.userName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="备注:" prop="desc">
              <el-input
                v-model="FromData.desc"
                type="textarea"
                placeholder="请输入备注 (不超过40字)"
                :autosize="{ minRows: 5, maxRows: 6 }"
              />
            </el-form-item>
          </el-form>
        </div>
      </template>
    </ADDdialog>
    <!-- 补货详情 -->
    <ADDdialog
    :within-dialog-visible="WithinDialogVisible"
    title="补货详情"
    @CloseDia="CloseDiaFn"
    @OpenDia="OpenDia">
    <template #Within>
          <div>
            <el-scrollbar style="height: 330px;" wrap-style="overflow-x:hidden;">
            <!-- 表单内容 -->
            <el-table
              :data="RepleniShmentDetailsData"
              style="width: 150%"
              :header-cell-style="headerStyleEvent"
            >
              <el-table-column
                label="货道编号"
                prop="channelCode"
                width="100%"
              />
              <el-table-column
                label="商品名称"
                prop="sku.skuName"
                width="100%"
              >
              <template #default="scope">
                {{scope.row.sku ?  scope.row.sku.skuName : '-'}}
              </template>
            </el-table-column>

              <el-table-column
                label="当前数量"
                prop="currentCapacity"
                width="100%"
              >
              <template #default="scope">
                {{scope.row.sku ? scope.row.currentCapacity : '-'}}
              </template>
            </el-table-column>

              <el-table-column label="还可添加" prop="nums" width="100%">
                <template #default="scope">
                  {{scope.row.sku ? scope.row.nums : '-'}}
                </template>
              </el-table-column>
              <el-table-column label="补满数量" width="200%">
                <template #default="scope">
                  <div v-if="scope.row.sku">
                    <el-input-number
                    v-model="scope.row.expectCapacity"
                    :max="scope.row.numsss"
                    :min="0"
                    @change="handleChange(scope.row)"
                    controls-position="right"
                  ></el-input-number>
                  </div>
                 <div v-else>货道暂无商品</div>
                </template>
              </el-table-column>
            </el-table>
          </el-scrollbar>
          </div>
        </template>
      </ADDdialog>
      <ADDdialog :ConfigDialogVisible="ConfigDialogVisible" title="工单配置" @CloseDia="CloseDiaFn"
    @OpenDia="OpenDia">
        <template #configuration>
          <span style="margin-right: 10px;">补货警戒线： </span>
            <el-input-number
                    v-model="WarningValu"
                    :max="100"
                    :min="10"
                    controls-position="right"
                    style="width: 450px"
                  ></el-input-number>
        </template>
      </ADDdialog>
      <ADDdialog :MsgDialogVisible="MsgDialogVisible"  title="工单详情" @CloseDia="CloseDiaFn"
    @OpenDia="OpenDia">
        <template #xq>
          <div class="xqBox">
            <div class="leftBox"><img :src="OrderMeg.icon" alt=""><span>{{OrderMeg.text}}</span></div>
              <span class="RightImg"><img :src="OrderMeg.img" alt=""></span>
          </div>
          <div class="ContentBox">
            <el-form :model="OrderMeg">
              <el-row>
                <el-col :span="12" >
                <el-form-item label="设备编号：" prop="taskCode" >
                  {{OrderMeg.taskCode}}
                </el-form-item>
                </el-col>
                <el-col :span="12">
                <el-form-item label="创建日期：" prop="createTime">
                  {{OrderMeg.createTime}}
                </el-form-item>
                </el-col>
                <el-col :span="12" v-if="OrderMeg.updateTime">
                <el-form-item label="取消日期：" prop="updateTime">
                  <template #label>
                    <span>{{PropsData.data.taskStatus === 3 ? '取消日期：' : '完成日期：'}}</span>
                  </template>
                  {{OrderMeg.updateTime}}
                </el-form-item>
                </el-col>
                <el-col :span="12">
                <el-form-item label="运营人员：" prop="userName">
                  {{OrderMeg.userName}}
                </el-form-item>
                </el-col>
                <el-col :span="12">
                <el-form-item label="工单类型：" prop="taskType" >
                  {{OrderMeg.taskType}}
                </el-form-item>
                </el-col>
                <el-col :span="12">
                <el-form-item label="补货数量：" prop="taskCode">
                  <el-link type="primary" :underline="false" style="display: block;" @click="RepleniShmentMegFn(OrderMeg)">补货详情</el-link>
                </el-form-item>
                </el-col>
                <el-col :span="12">
                <el-form-item label="工单方式：" prop="createType">
                  {{OrderMeg.createType}}
                </el-form-item>
                </el-col>
                <el-col :span="12">
                <el-form-item label="备注：" prop="desc">
                  <template #label>
                    <span>{{OrderMeg.taskStatus === 3 ? '取消原因：' : '备注：'}}</span>
                  </template>
                  {{OrderMeg.desc}}
                </el-form-item>
                </el-col>
          </el-row>
          </el-form>
          <el-button type="primary" size="small" class="gdpz" v-if="OrderMeg.BtnText"
          @click="toggle(OrderMeg)">{{OrderMeg.BtnText}}</el-button>
        </div>
        </template>
      </ADDdialog>
      <ADDdialog :RepleniShment="RepleniShment" title="补货详情" @CloseDia="CloseDiaFn">
        <template #Replen>
          <el-scrollbar style="height: 330px;" wrap-style="overflow-x:hidden;">
            <el-table :data="RepleniShmentData" :header-cell-style="headerStyleEvent">
              <el-table-column
                prop="channelCode"
                label="货道编号"

                align="center">
              </el-table-column>
              <el-table-column
                prop="skuName"
                label="商品"

                align="center">
              </el-table-column>
              <el-table-column
                prop="expectCapacity"
                label="补货数量"

                align="center">
              </el-table-column>
            </el-table>
          </el-scrollbar>
        </template>
      </ADDdialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { MessageBox, Message } from 'element-ui'
// VUEX模块化使用辅助函数
import { createNamespacedHelpers } from 'vuex'
import {
  SetValueRequest, GetOrderMegRequest, OperatorsRequest,
  CreateJobRequest, WarningValueRequest, GetOrderTypeRequest, RemoveOrderMegRequest, RepleniShmentDetailsRequest
} from '@/api'
const { mapActions, mapMutations, mapState } = createNamespacedHelpers('publics')
export default {
  data () {
    return {
      // 外弹出框
      OutsideDialogVisible: false,
      // 内弹出框
      WithinDialogVisible: false,
      // 工单配置
      ConfigDialogVisible: false,
      // 工单详情
      MsgDialogVisible: false,
      // 补货详情
      RepleniShment: false,
      // 定时器
      timer: null,
      // 预警值
      WarningValu: 0,
      // 补货详情
      RepleniShmentData: [],
      // 工单详情数据
      OrderMeg: {
        icon: null,
        img: null,
        text: ''
      },
      // 运营人员
      OperatorsData: [],
      // 表单数据
      FromData: {
        createType: 1,
        innerCode: '',
        userId: this.$store.state.user.UserLoginData.userId,
        productType: '',
        desc: '',
        details: [],
        assignorId: '',
        num: ''
      },
      // 效验数据
      departRules: {
        innerCode: [
          { required: true, message: '此项目为必填项', trigger: ['blur', 'change'] },
          { min: 1, max: 15, message: '1 - 15个字符', trigger: ['blur', 'change'] }
        ],
        productType: [
          { required: true, message: '此项目为必填项', trigger: ['blur', 'change'] }
        ],
        assignorId: [
          { required: true, message: '此项目为必填项', trigger: ['blur', 'change'] }
        ],
        desc: [
          { required: false, message: '此项目为必填项', trigger: ['blur', 'change'] },
          { min: 1, max: 15, message: '1 - 15个字符', trigger: ['blur', 'change'] }
        ]
      },
      // 补货详情
      RepleniShmentDetailsData: [],
      // 工单类型
      GetOrderTypeData: [],
      // 工单回显数据
      GDHXData: []
    }
  },
  async created () {
    // 工单类型
    const res1 = await GetOrderTypeRequest()
    this.GetOrderTypeData = res1.data
    // 工单状态
    await this.AcOrderStatus()
    this.OrderRequest()
  },
  methods: {
    ...mapActions(['AcOrderStatus', 'AcRepleniShmentMeg', 'AcOrderSearch']),
    ...mapMutations(['MaAddnum', 'MaAeenum', 'MaNum', 'MaInputFn', 'MaOrder', 'MaDropDown']),
    // 开启弹窗
    OpenDiaFn (item) {
      if (item === '1') {
        this.OutsideDialogVisible = true
      }
    },
    // 表格头回调函数
    headerStyleEvent () {
      return 'background-color:#f3f6fb'
    },
    // 售货机详情
    ReplenishmentFn (item) {
      this.$refs.departRef.validate(async (val) => {
        if (val) {
          const res = await RepleniShmentDetailsRequest(this.FromData.innerCode)
          console.log(res, '售货机')
          this.RepleniShmentDetailsData = res.data
          this.remaining()
          this.WithinDialogVisible = true
        }
      })
    },
    // 补货详情
    async RepleniShmentMegFn (item) {
      this.RepleniShment = true
      const res = await this.AcRepleniShmentMeg(item.taskId)
      console.log(res, '补货')
      this.RepleniShmentData = res.data
    },
    // 工单请求
    async OrderRequest () {
      await this.AcOrderSearch(this.PropsData.Order)
    },
    // 提交创建工单
    async OpenDia (item) {
      if (item !== '1') {
        this.WithinDialogVisible = false
        if (item === '3') {
          this.ConfigDialogVisible = false
          await SetValueRequest(this.WarningValu)
        }
        return
      }
      this.$refs.departRef.validate(async (vali) => {
        if (vali) {
          try {
            const res = await CreateJobRequest(this.FromData)
            console.log(res.data === true)
            if (res.data === true) {
              this.OutsideDialogVisible = false
              this.$message.success('添加成功')
            } else {
              console.log('？？？')
            }
          } catch (err) {
            console.log('？？？')
          }
        } else {
          // eslint-disable-next-line no-useless-return
          return
        }
      })
    },
    // 查询工单
    QueryFn () {
      this.MaNum()
      this.OrderRequest()
    },
    // 查看工单详情
    async CheckDetailsFn (item) {
      console.log(item)
      const { data } = await GetOrderMegRequest(item.taskId)
      this.GDHXData = data
      this.MsgDialogVisible = true
      if (data.taskStatusTypeEntity.statusName === '待办') {
        this.OrderMeg = {
          icon: '',
          img: 'http://likede2-admin.itheima.net/img/pic_1.834b274c.png',
          text: '待办',
          taskCode: data.taskCode,
          userName: data.userName,
          createTime: dayjs(data.createTime).format('YYYY-MM-DD HH:mm:ss'),
          taskType: data.taskType.typeName,
          createType: data.createType ? '手动' : '自动',
          taskStatus: data.taskStatus,
          taskId: data.taskId,
          BtnText: '取消工单'
        }
      } else if (data.taskStatusTypeEntity.statusName === '进行') {
        this.OrderMeg = {
          icon: '',
          img: 'http://likede2-admin.itheima.net/img/pic_1.834b274c.png',
          text: '待办'
        }
      } else if (data.taskStatusTypeEntity.statusName === '取消') {
        this.OrderMeg = {
          icon: '',
          img: 'http://likede2-admin.itheima.net/img/pic_3.e8208e34.png',
          text: '取消',
          taskCode: data.taskCode,
          userName: data.userName,
          createTime: dayjs(data.createTime).format('YYYY-MM-DD HH:mm:ss'),
          updateTime: dayjs(data.updateTime).format('YYYY-MM-DD HH:mm:ss'),
          taskType: data.taskType.typeName,
          desc: data.desc,
          createType: data.createType ? '手动' : '自动',
          taskStatus: data.taskStatus,
          taskId: data.taskId,
          innerCode: data.innerCode,
          BtnText: '重新创建'
        }
      } else {
        this.OrderMeg = {
          icon: '',
          img: 'http://likede2-admin.itheima.net/img/pic_4.3b5af41c.png',
          text: '完成',
          taskCode: data.taskCode,
          userName: data.userName,
          createTime: dayjs(data.createTime).format('YYYY-MM-DD HH:mm:ss'),
          updateTime: dayjs(data.updateTime).format('YYYY-MM-DD HH:mm:ss'),
          taskType: data.taskType.typeName,
          desc: data.desc,
          taskStatus: data.taskStatus,
          taskId: data.taskId,
          createType: data.createType ? '手动' : '自动'
        }
      }
    },
    // 预警阈值
    async configurationFn () {
      this.ConfigDialogVisible = true
      const res = await WarningValueRequest()
      this.WarningValu = res.data
    },
    // 工单详情按钮
    async toggle (item) {
      if (item.taskStatus === 1) {
        MessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          // 删除工单
          try {
            await RemoveOrderMegRequest(item)
            Message({
              type: 'success',
              message: '删除成功!'
            })
            this.MsgDialogVisible = false
            this.OrderRequest()
          } catch (err) {
            Message.error(err)
          }
        }).catch(() => {
          Message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else if (item.taskStatus === 3) {
        const res = await this.AcRepleniShmentMeg(this.GDHXData.taskId)
        this.FromData = {
          innerCode: this.GDHXData.innerCode,
          desc: this.GDHXData.desc,
          productType: this.GDHXData.productTypeId,
          assignorId: this.GDHXData.assignorId,
          details: res.data
        }
        this.Operators()
        this.MsgDialogVisible = false
        this.OutsideDialogVisible = true
        console.log(this.FromData, this.GDHXData)
      }
    },
    // 运营人员
    async Operators () {
      if (this.FromData.innerCode === '' || !this.FromData.innerCode) return
      const res = await OperatorsRequest(this.FromData.innerCode)
      this.OperatorsData = res.data
      console.log(this.FromData)
    },

    // 关闭弹出层
    CloseDiaFn (item) {
      if (item === '5') {
        this.RepleniShment = false
        return
      }
      if (item === '1') {
        this.OutsideDialogVisible = false
        this.$refs.departRef.resetFields()
        // this.FromData = {}
      } else {
        this.WithinDialogVisible = false
        this.ConfigDialogVisible = false
        this.MsgDialogVisible = false
      }
    },
    // 计数器值
    remaining (val) {
      this.RepleniShmentDetailsData.forEach((item) => {
        // 还可添加
        this.$set(item, 'nums', item.maxCapacity - item.currentCapacity)
        // v-molde绑定的值
        this.$set(item, 'expectCapacity', item.maxCapacity - item.currentCapacity)
        // max值
        this.$set(item, 'numsss', item.maxCapacity - item.currentCapacity)
      })
    },
    // 计数器统计补货详情
    handleChange (val) {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.FromData.details.push({
          channelCode: val.channelCode,
          expectCapacity: val.expectCapacity,
          skuId: val.skuId,
          skuName: val.sku.skuName,
          skuImage: val.sku.skuImage
        })
      }, 2000)
      console.log(this.FromData)
    },
    // 输入限制只数组
    InputFn (a) {
      console.log(this.PropsData)
      this.MaInputFn()
    },
    // 下页，上页键
    TwoBtn () {
      this.MaAddnum()
      this.OrderRequest()
    },
    OneBtn () {
      this.MaAeenum()
      this.OrderRequest()
    }
  },
  computed: {
    ...mapState(['PropsData'])
  }
}
</script>
<style lang="less" scoped>

.txt {
  width: 100px;
}
.xqBox{
  // text-align: left;
  height:50px;
  width:100%;
  background-color: #f8f8f8;
  display: flex;
    justify-content: space-between;
    align-items: center;
    .RightImg{
      margin-right:80px;
    }
    .leftBox{
      margin-left:20px;
      display: flex;
    align-items: center;
    img{
      margin-right:15px;
    }
    }
}
.ContentBox{
  text-align: left;
      height:220px;
      margin:50px 0px 0px 50px;
      .gdpz {
        width: 15%;
        margin-left:35%;
        zoom:105%;
        margin-top:20px;
      border: #fff;
      background-color: #fbf4f0;
      color: #333;
    }
    .el-col{
      margin-top:-20px;
    }
    }
    /deep/ .has-gutter{
      background-color: pink !important;

    }
</style>
